package com.zqf.shiro.service;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zqf.shiro.pojo.User;
import com.zqf.shiro.pojo.UserRole;
import com.zqf.shiro.pojo.dto.UserDTO;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.security.auth.message.AuthException;

import com.zqf.shiro.mapper.UserMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * @Author zqf
 * @Date 2022/12/16 10:01
 * @Description: $description
 */
@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Resource
    private UserMapper userMapper;
    @Resource
    private UserRoleService userRoleService;


    @Transactional(rollbackFor = Exception.class)
    public Boolean addUser(UserDTO userDTO) throws AuthException {
        User user1 = this.getUserByUserName(userDTO.getUsername());
        if (ObjectUtils.isNotNull(user1)) {
            throw new AuthException("用户已存在");
        }
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        String password = new Md5Hash(userDTO.getPassword(), salt, 1024).toHex();
        User user = new User();
        user.setUsername(userDTO.getUsername());
        user.setSalt(salt);
        user.setPassword(password);
        user.setLocked(true);
        save(user);

        //保存用户角色关系
        List<UserRole>userRoles = new ArrayList<>();
        for (Long role : userDTO.getRoles()) {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(role);
            userRoles.add(userRole);
        }
        return userRoleService.saveBatch(userRoles);
    }

    public User getUserByUserName(String userName) {
        return userMapper.getUserByUserName(userName);
    }

    public Set<String> getUserWithPermission(String username) {
        return userMapper.getUserWithPermission(username);
    }


    public Set<String> queryUserRoles(Long id) {
        return userRoleService.queryUserRoles(id);
    }
}

